package com.situ.mall.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.mall.constant.MallConstant;
import com.situ.mall.entity.Product;
import com.situ.mall.vo.CartItemVO;
import com.situ.mall.vo.CartVO;

public class CartUtil {
	/**
	 * a、第一个方法，将购物车信息转换为CartVO
	 * @param request
	 * @return
	 */
	public static CartVO getCartVOFromCookie(HttpServletRequest request) {
		CartVO cartVO = null;
		ObjectMapper objectMapper = new ObjectMapper();
		//对象不为null转换
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		//将购物车的cookie拿出来
		Cookie[] cookies = request.getCookies();
		if (null != cookies && cookies.length != 0) {
			for (Cookie cookie : cookies) {
				if (MallConstant.CART_COOKIE.equals(cookie.getName())) {
					//找到cookie购物车信息
					String value = cookie.getValue();
					try {
						cartVO = objectMapper.readValue(value, CartVO.class);
					} catch (JsonParseException e) {
						e.printStackTrace();
					} catch (JsonMappingException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return cartVO;
	}

	
	
	/**
	 * c、将CartVO对象设置到cookie(类似修改完再放回去)
	 * @param cartVO
	 * @param response
	 */
	public static void setCartVOToCookie(CartVO cartVO, HttpServletResponse response) {
		ObjectMapper objectMapper = new ObjectMapper();
		// 只有对象中不为null才转换
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		// 将cartVo对象以json形式放到cookie
		StringWriter stringWriter = new StringWriter();
		try {
			objectMapper.writeValue(stringWriter, cartVO);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 将购物车json放到cookie
		Cookie cookie = new Cookie(MallConstant.CART_COOKIE, stringWriter.toString());
		// 设置cookie的存储时间
		cookie.setMaxAge(60 * 60 * 24);// 单位秒
		// 设置cookie路径
		cookie.setPath("/");
		// 将cookie发送到浏览器
		response.addCookie(cookie);
	}
	
}
